//
//  VideoVC.m
//  OpenEyes
//
//  Created by dllo on 15/9/9.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "VideoVC.h"
#import "VideoModel.h"
#import "MoviewDailyCell.h"
#define kReuse @"reuse"
#import "HTTPTool.h"
#import "MovieDetaiVC.h"
#define KCollectionReuse @"collectionReuse"
#import "plViewController.h"
typedef NS_ENUM(NSInteger, DataType) {
    DataTypeAdd,
    DataTypeRefresh
};


@interface VideoVC ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, strong)MBProgressHUD *hud;
@property(nonatomic, assign)DataType dataType;

@property(nonatomic, strong)UICollectionView *dailyCollection;
@property(nonatomic, strong)UITableView *dailyMainTable;
@property(nonatomic, strong)NSMutableArray *dailyListArr;

@property(nonatomic, strong)NSArray *monthArr;

@property(nonatomic, strong)NSDate *dateMark;

@property(nonatomic, copy)NSString *nextPageUrl;
@end

@implementation VideoVC
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dateMark = [NSDate date];
        self.monthArr = @[@"Jan.", @"Feb.", @"Mar.", @"Apr.", @"May.", @"Jun.", @"Jul.", @"Aug.", @"Sep.", @"Oct.", @"Nov.", @"Dec."];
        self.dailyListArr = [NSMutableArray array];
        self.dataType = DataTypeRefresh;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor blackColor];
    
    self.hud = [[MBProgressHUD alloc] init];
    self.hud.color = [UIColor clearColor];
//    [self.view addSubview:self.hud];
    [self.hud show:YES];
 
    
    if (self.classUrlStr == nil) {
        [self createTableView];
        [self creatTopView];
        [self createData];
        //下拉刷新
        
        __weak typeof(self) videoBlock = self;
        
        [self.dailyMainTable addLegendHeaderWithRefreshingBlock:^{
            videoBlock.dataType = DataTypeRefresh;
            [videoBlock.hud show:YES];
            [videoBlock createData];
            
        }];
        
//               self.dailyMainTable.header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
//        }];

        //上拉加载
        
        [self.dailyMainTable addLegendFooterWithRefreshingBlock:^{
            
            videoBlock.dataType = DataTypeAdd;
            videoBlock.dateMark = [NSDate dateWithTimeInterval: - 10 * 24 * 3600 sinceDate:videoBlock.dateMark];
            [videoBlock jsonForDataWithStr:[NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/feed?date=%@&num=10", [videoBlock changeTimeFormat:videoBlock.dateMark]]];
        }];
        
//        self.dailyMainTable.footer = [MJRefreshFooter footerWithRefreshingBlock:^{
//        }];
    }else{
    
        [self createTableView];
        self.dailyMainTable.frame = CGRectMake(0, 0, WIDTH, HEIGHT - 64);
        NSString *str = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/videos?categoryName=%@&num=10", [self.classUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        [self.dailyListArr removeAllObjects];
        [self createClassData:str];
        
    }
}

    
    

//- (void)creatTopView
//{
//   
//    self.rightBackView.image = [UIImage imageNamed:@"chakan2"];
//}
- (void)creatTopView
{
    [super creatTopView];
    self.rightBackView.image = [UIImage imageNamed:@"chakan2"];
}
- (void)rightBuAction:(UIButton *)button
{
    NSIndexPath *index = [[self.dailyMainTable indexPathsForVisibleRows] firstObject];
    UITableViewCell *cell = [self.dailyMainTable cellForRowAtIndexPath:index];
    NSArray *arr = self.dailyListArr[index.section];
    if (cell.frame.origin.y < self.dailyMainTable.contentOffset.y - 40) {
        if (index.row == arr.count - 1) {
            index = [NSIndexPath indexPathForRow:0 inSection:index.section + 1];
        }else{
            index = [NSIndexPath indexPathForRow:index.row + 1 inSection:index.section];
        }
    }
    [self tableView:self.dailyMainTable didSelectRowAtIndexPath:index];
}
#pragma mark -
#pragma mark 数据解析
- (void)createData
{
    NSString *timeId = [self changeTimeFormat:[NSDate date]];
    NSString *urlStr = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/feed?date=%@&num=10", timeId];
    [self jsonForDataWithStr:urlStr];
}
- (void)jsonForDataWithStr:(NSString *)urlStr
{
    [HTTPTool get:urlStr body:nil httpResult:JSON success:^(id result) {
        if (self.dataType == DataTypeRefresh) {
            [self.dailyListArr removeAllObjects];
        }
        for (NSDictionary *dic in result[@"dailyList"]) {
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *tempDic in dic[@"videoList"]) {
               VideoModel *model = [[VideoModel alloc] init];
                [model setValuesForKeysWithDictionary:tempDic];
                //时间处理
                NSInteger time = [tempDic[@"date"] integerValue] / 1000 + 3600 * 8;
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
                model.date = [self changeTimeFormat:date];
                NSInteger a = [[[self changeTimeFormat:date] substringWithRange:NSMakeRange(4, 2)] integerValue];
                model.date = [NSString stringWithFormat:@"- %@%@ -", self.monthArr[a - 1], [[self changeTimeFormat:date] substringFromIndex:6]];
                
                [arr addObject:model];
            }
            
            [self.dailyListArr addObject:arr];
        }
        
        [self addFileToCacheWithArr:self.dailyListArr key:@"dailyListArr"];
        [self.dailyMainTable reloadData];
        [self.dailyMainTable.header endRefreshing];
        [self.dailyMainTable.footer endRefreshing];
        [self.hud hide:YES];
    } failure:^(NSError *error) {
        NSLog(@"解析失败");
        self.dailyListArr = [self getArrFromCacheWithKey:@"dailyListArr"];
        [self.dailyMainTable reloadData];
        [self.dailyMainTable.header endRefreshing];
        [self.dailyMainTable.footer endRefreshing];
        [self.hud hide:YES];
    }];
    
}
- (void)createClassData:(NSString *)urlStr
{
    
    [HTTPTool get:urlStr body:nil httpResult:JSON success:^(id result) {
        if (self.dataType == DataTypeRefresh) {
            [self.dailyListArr removeAllObjects];
        }
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *tempDic in result[@"videoList"]) {
            VideoModel *model = [[VideoModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            NSInteger time = [tempDic[@"date"] integerValue] / 1000 + 3600 * 8;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
            model.date = [self changeTimeFormat:date];
            [arr addObject:model];
        }
        self.nextPageUrl = result[@"nextPageUrl"];
        [self.dailyListArr addObject:arr];
        [self addFileToCacheWithArr:self.dailyListArr key:self.classUrlStr];
        [self.dailyMainTable reloadData];
        [self.dailyMainTable.footer endRefreshing];
    } failure:^(NSError *error) {
        self.dailyListArr = [self getArrFromCacheWithKey:self.classUrlStr];
        [self.dailyMainTable reloadData];
        [self.dailyMainTable.footer endRefreshing];
    }];
    
    
}

#pragma mark -
#pragma mark 时间处理
- (NSString *)changeTimeFormat:(NSDate *)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *str = [formatter stringFromDate:date];
    return str;
}
#pragma mark -
#pragma mark 创建table
- (void)createTableView
{
    self.dailyMainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    self.dailyMainTable.dataSource = self;
    self.dailyMainTable.delegate = self;
    self.dailyMainTable.separatorStyle = 0;
    [self.dailyMainTable registerClass:[MoviewDailyCell class] forCellReuseIdentifier:kReuse];
    [self.view addSubview:self.dailyMainTable];
    
    
    
//    
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame = CGRectMake(W * 20, H * 500, 30, 30);
//    [button setImage:[UIImage imageNamed:@"iconfont-fenlei"] forState:UIControlStateNormal];
//    button.alpha = 0.8;
//    button.layer.masksToBounds = YES;
//    button.layer.borderColor = [[UIColor whiteColor] CGColor];
//    [button addTarget:self action:@selector(pushClick:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
//    
}
//-(void)pushClick:(UIButton *)sender{
//    
//    if (_classUrlStr == nil) {
//        plViewController * pl =[[plViewController alloc]init];
//        [self.navigationController pushViewController:pl animated:YES];
//    }else{
//        [self.navigationController popViewControllerAnimated:YES];
//    }
//    
//    
//    
//    
//}
#pragma mark -
#pragma mark table
//row数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = self.dailyListArr[section];
    return arr.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    VideoModel *model = [self.dailyListArr[section] firstObject];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    label.text = model.date;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:20];
    [label setBackgroundColor:[UIColor clearColor]];
    return label;
}
//section数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dailyListArr.count;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MoviewDailyCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuse];
    VideoModel *model = self.dailyListArr[indexPath.section][indexPath.row];
    
    NSString *name = @"gif.gif";
    NSString *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage sd_animatedGIFWithData:imageData];

    
    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:model.coverForFeed] placeholderImage:image];
    cell.titleLabel.text = model.title;
    cell.detailLabel.text = [NSString stringWithFormat:@"%@ / %@", model.category, model.duration];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.classUrlStr != nil) {
        return 0.1;
    }
    if (section == 0) {
        return 0.1;
    }
    
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MovieDetaiVC *vc = [[MovieDetaiVC alloc] init];
    [vc setModalTransitionStyle:2];
    vc.dailyListArr = self.dailyListArr;
    vc.movieIndexPath = indexPath;
    [self presentViewController:vc animated:YES completion:^{
        
    }];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.classUrlStr == nil) {
        if (scrollView.contentOffset.y > 40 + 1000) {
            NSIndexPath *path = [self.dailyMainTable indexPathForRowAtPoint:CGPointMake(0, scrollView.contentOffset.y + 1)];
            VideoModel *model = [self.dailyListArr[path.section] firstObject];
            self.leftBuName.text = [model.date substringWithRange:NSMakeRange(2, 6)];
            self.leftBuName.font = [UIFont fontWithName:@"AmericanTypewriter" size:13];
        }else{
            self.leftBuName.text = @"Today";
            self.leftBuName.font = [UIFont fontWithName:@"AmericanTypewriter" size:13];
        }
    }
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
